<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Component\SendMailController;
use App\Http\Requests\Admin\GoodsRequest;
use App\Mail\NoticeMail;
use App\Model\Creator;
use App\Model\goods;
use App\Model\Genre;
use App\Model\GoodsPutaway;
use App\User;
use DB;
use Illuminate\Http\Request;
use Webpatser\Uuid\Uuid;
use App\Jobs\SendEmail;
use App\Mail\TakeOffNotice;
use App\Model\Order;

class GoodsController extends MasterController
{

    protected $takeRows = 100;

    /**
     * Display a listing of the resource.
     * get
     * @return \Illuminate\Http\Response
     */


    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $goods = DB::table('goods_v')->where('status', '=', 1)
            ->take($this->takeRows)->orderBy('created_at')->get();
        $goodsCount = DB::table('goods_v')->where('status', '=', 1)->count('*');
        $genres = Genre::all();
        $creators = Creator::all();
        $data = array(
            'goods' => $goods,
            'goodsCount' => $goodsCount,
            'genres' => $genres,
            'creators' => $creators,
        );
        return view('admin.goods.goods', compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     * get
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     *
     * Store a newly created resource in storage.
     * post
     * @param GoodsRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     *
     */
    public function store(GoodsRequest $request)
    {
        $upload = $request->file;
        $path = '';
        if ($upload->isValid()) {
            $path = '/images/goods/' . $upload->store('', 'goods');
        }
        Goods::create([
            'id' => Uuid::generate(4),
            'name' => $request['name'],
            'author' => $request['author'],
            'intro' => $request['intro'],
            'size' => $request['size'],
            'price' => $request['price'],
            'imgUrl' => $path,
            'genre_id' => $request['genre_id'],
            'creator_id' => $request['creator_id'],
            'stars' => 0,
            'status' => 1,
        ]);

        return parent::success('添加成功！');
    }

    /**
     * Display the specified resource.
     * get
     * @param  int $id
     * @return \Illuminate\Http\Response
     */

    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     * get
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    //修改作品图片
    public function changeImg(Request $request)
    {
        $file = $request->file;
        $path = '';
        if ($file->isValid()) {
            $path = '/images/goods/' . $file->store('', 'goods');
        }
        Goods::where('id', $request['id'])->update(['imgUrl' => $path]);
        return response()->json([
            'path' => $path
        ]);
    }

    /**
     *  * Update the specified resource in storage.
     * put patch
     * @param GoodsRequest $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(GoodsRequest $request, $id)
    {
        Goods::where('id', $id)->update([
            'name' => $request['name'],
            'author' => $request['author'],
            'price' => $request['price'],
            'size' => $request['size'],
            'intro' => $request['intro'],
            'genre_id' => $request['genre_id'],
            'creator_id' => $request['creator_id']
        ]);
        $goods = DB::table('goods_v')->where('id', $id)->first();
        return response()->json([
            'goods' => $goods,
            'message' => '作品信息已修改！'
        ], 200);
    }

    /**
     * Remove the specified resource from storage.
     * delete
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $count=Order::where('goods_id',$id)->where('status','<>',4)->where('status','<>',5)->count('*');
        if ($count>0){
            return parent::error('删除失败，该作品存在正在进行中订单！');
        }
        $i = DB::table('goods_v')->where('id', $id)->select('user_id', 'name')->first();
        $user = User::where('id', $i->user_id)->select('name', 'email')->first();
        Goods::where('id', $id)->forceDelete();
        $message = '您的作品《' . $i->name . '》因涉嫌违反本站相关规定,现已将其删除,具体原因请联系网站管理员';
        $mail = (new NoticeMail($user->name, $message, '作品删除通知'))
            ->onConnection('redis')
            ->onQueue('emails');
        SendEmail::dispatch($user->email, $mail);
        return parent::success('操作成功，已通过邮件通知用户');
    }

    //下架

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function takeOff(Request $request)
    {
        $count=Order::where('goods_id',$request['id'])->where('status','<>',4)->where('status','<>',5)->count('*');
        if ($count>0){
            return parent::error('下架失败，该作品存在正在进行中订单！');
        }
        $goods = Goods::where('id', '=', $request['id'])->first();
        Goods::where('id', $request['id'])->forceDelete();
        GoodsPutaway::create([
            'id' => $goods->id,
            'author' => $goods->author,
            'price' => $goods->price,
            'size' => $goods->size,
            'intro' => $goods->intro,
            'name' => $goods->name,
            'imgUrl' => $goods->imgUrl,
            'genre_id' => $goods->genre_id,
            'creator_id' => $goods->creator_id,
            'status' => false,
        ]);
        $user = User::where('id', $request['user_id'])->select('email', 'name')->first();
        $to = $user['email'];
        $username = $user['name'];
        $message = "您的作品 《" . $request['name'] . "》已被下架！";
        $mail = (new TakeOffNotice($message, $request['reason'], $username))
            ->onConnection('redis')
            ->onQueue('emails');
        SendEmail::dispatch($to, $mail);
        return parent::success('操作成功！已向用户发送邮箱通知');
    }

    // 1 当下架或删除的数据造成前端显示当前分页数据条数未填充满 19/20 即每页20条数据 此页只有19条的情况
    // 2 当下架或删除的数据为此前获取数据的最后一页中的数据，且此前数据并未完全获取，即总数据有200条，此前加载了100条，每页20条，在第五页删除了一条数据
    //满足以上个条件 访问此方法，获取新数据以填充
    public function fill($start, $genre_id, $searchText)
    {
        $filters = [];
        if ($genre_id != 'null') {
            $item['key'] = 'genre_id';
            $item['value'] = $genre_id;
            array_push($filters, $item);
        }

        if ($searchText != 'null') {
            $item['key'] = 'name';
            $item['value'] = $searchText;
            array_push($filters, $item);
        }

        $filterCount = count($filters);
        $goods = null;

        $end = $this->takeRows + 1;
        if ($filterCount == 0) {
            $goods = DB::table('goods_v')
                ->where('status', '=', 1)
                ->skip($start)->take($end)->orderBy('created_at')->get();
        } elseif ($filterCount = 1) {
            $operrator = 'like';
            $value = '%' . $filters[0]['value'] . '%';
            if ($genre_id != 'null') {
                $operrator = '=';
                $value = $filters[0]['value'];
            }
            $goods = DB::table('goods_v')
                ->where('status', '=', 1)
                ->where($filters[0]['key'], $operrator, $value)
                ->skip($start)->take($end)->orderBy('created_at')->get();
        } else {
            $goods = DB::table('goods_v')
                ->where('status', '=', 1)
                ->where($filters[0]['key'], '=', $filters[0]['value'])
                ->where($filters[1]['key'], 'like', '%' . $filters[1]['value'] . '%')
                ->skip($start)->take($end)->orderBy('created_at')->get();
        }

        return parent::successWithData($goods);
    }


    /**
     *
     *  下一页 数据未加载时 访问此方法加载下一组数据
     * @param $start
     * @param $end
     * @param $genre_id
     * @param $searchText
     * @return \Illuminate\Http\JsonResponse
     */
    //加载当前页数据
    public function showNew($start, $end, $genre_id, $searchText)
    {

        $getCount = $end - $start;
        if ($getCount < $this->takeRows) {
            $end = $this->takeRows;
        }
        $filters = [];
        if ($genre_id != 'null') {
            $item['key'] = 'genre_id';
            $item['value'] = $genre_id;
            array_push($filters, $item);
        }

        if ($searchText != 'null') {
            $item['key'] = 'name';
            $item['value'] = $searchText;
            array_push($filters, $item);
        }

        $filterCount = count($filters);
        $goods = null;
        if ($filterCount == 0) {
            $goods = DB::table('goods_v')
                ->where('status', '=', 1)
                ->skip($start)->take($end)->orderBy('created_at')->get();
        } elseif ($filterCount = 1) {
            $operrator = 'like';
            $value = '%' . $filters[0]['value'] . '%';
            if ($genre_id != 'null') {
                $operrator = '=';
                $value = $filters[0]['value'];
            }
            $goods = DB::table('goods_v')
                ->where('status', '=', 1)
                ->where($filters[0]['key'], $operrator, $value)
                ->skip($start)->take($end)->orderBy('created_at')->get();
        } else {
            $goods = DB::table('goods_v')
                ->where('status', '=', 1)
                ->where($filters[0]['key'], '=', $filters[0]['value'])
                ->where($filters[1]['key'], 'like', '%' . $filters[1]['value'] . '%')
                ->skip($start)->take($end)->orderBy('created_at')->get();
        }

        return parent::successWithData($goods);
    }

    //搜索
    public function search($genre_id, $searchText)
    {
        $filters = [];
        if ($genre_id != 'null') {
            $item['key'] = 'genre_id';
            $item['value'] = $genre_id;
            array_push($filters, $item);
        }

        if ($searchText != 'null') {
            $item['key'] = 'name';
            $item['value'] = $searchText;
            array_push($filters, $item);
        }

        $filterCount = count($filters);
        $goods = null;
        $goodsCount = 0;
        if ($filterCount == 0) {
            $goods = DB::table('goods_v')
                ->where('status', '=', 1)
                ->take($this->takeRows)->orderBy('created_at')->get();
            $goodsCount = DB::table('goods_v')->count('*');
        } elseif ($filterCount == 1) {
            $operrator = 'like';
            $value = '%' . $filters[0]['value'] . '%';
            if ($genre_id != 'null') {
                $operrator = '=';
                $value = $filters[0]['value'];
            }
            $goods = DB::table('goods_v')
                ->where('status', '=', 1)
                ->where($filters[0]['key'], $operrator, $value)
                ->take($this->takeRows)->orderBy('created_at')->get();
            $goodsCount = DB::table('goods_v')
                ->where('status', '=', 1)
                ->where($filters[0]['key'], $operrator, $value)->count('*');
        } else {
            $goods = DB::table('goods_v')
                ->where('status', '=', 1)
                ->where($filters[0]['key'], '=', $filters[0]['value'])
                ->where($filters[1]['key'], 'like', '%' . $filters[1]['value'] . '%')
                ->take($this->takeRows)->orderBy('created_at')->get();
            $goodsCount = DB::table('goods_v')
                ->where('status', '=', 1)
                ->where($filters[0]['key'], '=', $filters[0]['value'])
                ->where($filters[1]['key'], 'like', '%' . $filters[1]['value'] . '%')->count('*');
        }
        return response()->json([
            'status_code' => 200,
            'goods' => $goods,
            'goodsCount' => $goodsCount
        ], 200);
    }
}
